package com.milk.milkmedia.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.milk.milkmedia.api.ConstantField;
import com.milk.milkmedia.dao.DBManager;
import com.milk.milkmedia.dao.MusicInfoDB;
import com.milk.milkmedia.ui.HomePageActivity;
import com.milk.milkmedia.ui.MusicPlayAcitivity;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 微安 on 2015/8/14.
 */
public class MusicPlayService extends Service {

    public static MediaPlayer iMediaPlay;
    private String iMusicPath;
    private int mPosition;
    private String mAction;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private final IBinder binder = new MyBinder();
    private boolean mIsPlay = true;
    private int mTotalCount;

    public class MyBinder extends Binder {
        public MusicPlayService getService() {
            return MusicPlayService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        iMediaPlay = new MediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initBroadCast();
        Log.e(HomePageActivity.Tag,"启动 服务");
        return super.onStartCommand(intent, flags, startId);
    }

    class MusicPlayThread extends Thread {
        @Override
        public void run() {
            super.run();
            iMediaPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
            if (mAction.equals(ConstantField.ACTION_STOP)) {
                mIsPlay = false;
                iMediaPlay.pause();
            } else if (mAction.equals(ConstantField.ACTION_PLAY)) {
                PlayMusic(iMusicPath);
                mIsPlay = true;
            } else if (mAction.equals(ConstantField.ACTION_NEXT)) {
                PlayMusic(iMusicPath);
                mIsPlay = true;
            } else if (mAction.equals(ConstantField.ACTION_PREV)) {
                PlayMusic(iMusicPath);
                mIsPlay = true;
            }
            iMediaPlay.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mIsPlay = true;
                    Log.e(HomePageActivity.Tag, "模式是几" + ConstantField.MODE);
                    switch (ConstantField.MODE) {
                        case ConstantField.PLAY_LIST:
                            mPosition = mPosition + 1;
                            if (mPosition >= mTotalCount) {
                                mPosition = 0;
                            }
                            iMusicPath = queryPositionUrl(mPosition);
                            Log.e(HomePageActivity.Tag, "地址是" + iMusicPath);
                            PlayMusic(iMusicPath);
                            break;
                        case ConstantField.PLAY_SINGLE_LOOP:
                            PlayMusic(iMusicPath);
                            break;
                        case ConstantField.PLAY_REPEAT:
                            Log.e(HomePageActivity.Tag, "复读模式");
                            playRepeat();
                            iMediaPlay.stop();
                            break;
                        case ConstantField.PLAY_RANDOM:
                            Random r = new Random();
                            mPosition = r.nextInt(ConstantField.TIMER_COUNT) % mTotalCount;
                            iMusicPath = queryPositionUrl(mPosition);
                            Log.e(HomePageActivity.Tag, mPosition + "随机出来地址是" + iMusicPath);
                            PlayMusic(iMusicPath);
                            break;
                    }
                }
            });
        }
    }

    private void playRepeat() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        iMediaPlay.release();
    }

    /**
     * 根据地址播放音频
     *
     * @param path
     */
    public void PlayMusic(String path) {
        Intent lrcIntent = new Intent();
        try {
            if (mIsPlay == false) {
                Log.e(HomePageActivity.Tag, "位置" + iMediaPlay.getCurrentPosition());
                iMediaPlay.seekTo(iMediaPlay.getCurrentPosition());
                iMediaPlay.start();
            } else {
                iMediaPlay.reset();
                iMediaPlay.setDataSource(path);
                iMediaPlay.prepare();
                lrcIntent.setAction(ConstantField.ACTION_UPDATE);
                lrcIntent.putExtra("position", mPosition);
                sendBroadcast(lrcIntent);
                Log.e(HomePageActivity.Tag, "发送广播");
                iMediaPlay.start();
                MusicPlayAcitivity.iMusicSeekBar.setMax(iMediaPlay.getDuration());

            }
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    MusicPlayAcitivity.iMusicSeekBar.setProgress(iMediaPlay.getCurrentPosition());
                }
            };
            mTimer.schedule(mTimerTask, 0, 100);
        } catch (IOException e) {
            Log.e(HomePageActivity.Tag, "未能读取到音频文件");
        }
        mIsPlay = true;
    }

    private String queryPositionUrl(int position) {
        try {
            Dao<MusicInfoDB, String> musicInfoDB = DBManager.getInstance().getMusicInfoBDHelper().getDao(MusicInfoDB.class);
            List<MusicInfoDB> musicInfoDBs = musicInfoDB.queryBuilder().where().eq("id", position).query();
            mTotalCount = musicInfoDB.queryForAll().size();
            if (musicInfoDBs.size() != 0) {
                return musicInfoDBs.get(0).getUrl();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(HomePageActivity.Tag, "MusicListAdapter建立iMusicInfoDao错误");
        }
        return "null";
    }

    private void initBroadCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantField.ACTION);
        MusicPlayerReceiver broadcastReceiver = new MusicPlayerReceiver();
        registerReceiver(broadcastReceiver, filter);
    }

    class MusicPlayerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mAction = intent.getStringExtra("action");
            mPosition = intent.getIntExtra("position", 0);
            iMusicPath = queryPositionUrl(mPosition);
            Log.e(HomePageActivity.Tag, "广播收到的" + mPosition);
            MusicPlayThread musicPlayThread = new MusicPlayThread();
            musicPlayThread.start();
        }
    }
}
